﻿using System;
using ShureValidation.Language;

namespace ShureValidation.Rules
{
    /// <summary>
    /// Validates password. Minimum 5 characters long and both digits and letters.
    /// </summary>
    [LanguagePrompt("Password", "'{0}' must contain at least five characters, both digits and letters.")]
    [Serializable]
    public class PasswordRule : IRule
    {
        #region IRule Members

        /// <summary>
        /// Format an error message
        /// </summary>
        /// <param name="fieldName">Field (have already been translated)</param>
        /// <param name="rulesLanguage">Language prompts for validation rules</param>
        /// <returns>Error message formatted for the current language.</returns>
        public string Format(string fieldName, IModelLanguage rulesLanguage)
        {
            return string.Format(rulesLanguage["Password"], fieldName);
        }

        /// <summary>
        /// Checks if this rule support values of the specified format.
        /// </summary>
        /// <param name="type">Type of value</param>
        /// <returns><c>true</c> if the specified type can be validated; otherwise <c>false</c>.</returns>
        public bool SupportsType(Type type)
        {
            return typeof (string).IsAssignableFrom(type);
        }

        /// <summary>
        /// Validate a field value
        /// </summary>
        /// <param name="value">Value to validate</param>
        /// <returns><c>true</c> if validation was successful; otherwise <c>false</c>.</returns>
        public bool Validate(object value)
        {
            bool hasLetter = false;
            bool hasDigit = false;
            var temp = (string) value;
            if (temp.Length < 5)
                return false;

            foreach (char ch in temp)
            {
                if (char.IsDigit(ch))
                    hasDigit = true;
                if (char.IsLetter(ch))
                    hasLetter = true;
            }

            return hasLetter && hasDigit;
        }

        #endregion
    }
}